// 监控和日志配置

const winston = require('winston');
const path = require('path');

// 日志配置
const logConfig = {
  level: process.env.LOG_LEVEL || 'info',
  format: winston.format.combine(
    winston.format.timestamp({
      format: 'YYYY-MM-DD HH:mm:ss'
    }),
    winston.format.errors({ stack: true }),
    winston.format.json()
  ),
  defaultMeta: { 
    service: 'print-ad-system',
    environment: process.env.NODE_ENV || 'production'
  },
  transports: [
    // 控制台输出
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.simple()
      )
    }),
    
    // 错误日志文件
    new winston.transports.File({
      filename: path.join(__dirname, '../backend/logs/error.log'),
      level: 'error',
      maxsize: 20 * 1024 * 1024, // 20MB
      maxFiles: 5,
      tailable: true
    }),
    
    // 组合日志文件
    new winston.transports.File({
      filename: path.join(__dirname, '../backend/logs/combined.log'),
      maxsize: 20 * 1024 * 1024, // 20MB
      maxFiles: 10,
      tailable: true
    })
  ]
};

// 创建日志实例
const logger = winston.createLogger(logConfig);

// 性能监控配置
const performanceConfig = {
  // 响应时间监控
  responseTime: {
    enabled: true,
    threshold: 1000 // 1秒
  },
  
  // 内存监控
  memory: {
    enabled: true,
    threshold: 0.8 // 80%
  },
  
  // CPU监控
  cpu: {
    enabled: true,
    threshold: 0.8 // 80%
  },
  
  // 数据库监控
  database: {
    enabled: true,
    slowQueryThreshold: 1000 // 1秒
  }
};

// 健康检查配置
const healthCheckConfig = {
  interval: parseInt(process.env.HEALTH_CHECK_INTERVAL) || 30000,
  timeout: 5000,
  checks: {
    database: true,
    redis: true,
    oss: true,
    memory: true,
    disk: true
  }
};

// 告警配置
const alertConfig = {
  email: {
    enabled: process.env.ALERT_EMAIL_ENABLED === 'true',
    recipients: (process.env.ALERT_EMAIL_RECIPIENTS || '').split(','),
    smtp: {
      host: process.env.MAIL_HOST,
      port: parseInt(process.env.MAIL_PORT) || 587,
      auth: {
        user: process.env.MAIL_USER,
        pass: process.env.MAIL_PASS
      }
    }
  },
  
  webhook: {
    enabled: process.env.ALERT_WEBHOOK_ENABLED === 'true',
    url: process.env.ALERT_WEBHOOK_URL
  },
  
  thresholds: {
    errorRate: 0.05, // 5%
    responseTime: 2000, // 2秒
    memoryUsage: 0.85, // 85%
    cpuUsage: 0.85, // 85%
    diskUsage: 0.9 // 90%
  }
};

// 指标收集配置
const metricsConfig = {
  enabled: process.env.METRICS_ENABLED === 'true',
  interval: 60000, // 1分钟
  retention: 7 * 24 * 60 * 60 * 1000, // 7天
  
  // 业务指标
  business: {
    userRegistrations: true,
    adViews: true,
    pointsEarned: true,
    pointsConsumed: true,
    orders: true,
    revenue: true
  },
  
  // 系统指标
  system: {
    requests: true,
    responses: true,
    errors: true,
    latency: true,
    throughput: true
  }
};

module.exports = {
  logger,
  performanceConfig,
  healthCheckConfig,
  alertConfig,
  metricsConfig
};